package com.smile.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.smile.api.OperateLogApi;
import com.smile.api.OrganizationApi;
import com.smile.api.OssApi;
import com.smile.commons.action.ActionUtils;
import com.smile.commons.page.MyBatisPlusPageConverter;
import com.smile.commons.page.R;
import com.smile.commons.time.TimeUtils;
import com.smile.mapper.*;
import com.smile.model.domain.*;
import com.smile.model.dto.DroneDTO;
import com.smile.model.dto.request.*;
import com.smile.model.request.GetOrganizationByIdRequest;
import com.smile.model.response.GetOrganizationByIdResponse;
import com.smile.model.response.response.FlightDataResponseDTO;
import com.smile.model.response.response.GetAirportByIdResponseDTO;
import com.smile.model.response.response.GetAirportListResponseDTO;
import com.smile.model.response.response.PayloadDataResponseDTO;
import com.smile.request.AddOperateLogRequest;
import com.smile.service.AirportService;
import com.smile.service.CommonService;
import com.smile.service.MediaService;
import com.smile.service.PayloadService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MediaServiceImpl implements MediaService {

    @Autowired
    private MediaMapper mediaMapper;


    @Autowired
    private InspectionTaskMapper inspectionTaskMapper;
    @Autowired
    private CommonService commonService;

    @Autowired
    private PayloadService payloadService;

    private ReentrantLock reentrantLock = new ReentrantLock();
    @Autowired
    private FlightTaskMapper flightTaskMapper;
    @Autowired
    private DroneMapper droneMapper;

    @Override
    public Boolean addMedia(AddMediaRequestDTO addMediaRequestDTO) throws IOException{
        FeisuanMedia feisuanMedia = new FeisuanMedia();
        //查询出组织机构
        FlightDataResponseDTO flightDataResponseDTO = commonService.getFlightData(addMediaRequestDTO.getFlightId());

        //查询出当前是否建立目录
        QueryWrapper<FeisuanMedia> queryWrapper = new QueryWrapper();
        queryWrapper.eq("flight_id", addMediaRequestDTO.getFlightId());
        queryWrapper.eq("parent_id", 0);
        queryWrapper.last("limit 1");
        FeisuanMedia feisuanMedia1 = mediaMapper.selectOne(queryWrapper);
        PayloadDataResponseDTO payloadDataResponseDTO = payloadService.getPayloadData(addMediaRequestDTO.getGateway());
        Long parentId = (long) 0;
        if(ObjectUtil.isNull(feisuanMedia1)){
            long timestamp = System.currentTimeMillis(); // 获取当前时间的毫秒时间戳
            Instant instant = Instant.ofEpochMilli(timestamp);
            ZoneId zoneId = ZoneId.of("Asia/Shanghai");
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日HH时mm分ss秒", Locale.SIMPLIFIED_CHINESE);
            QueryWrapper<FeisuanFlightTask>  queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("flight_id", addMediaRequestDTO.getFlightId());
            queryWrapper1.last("limit 1");
            FeisuanFlightTask feisuanFlightTask = flightTaskMapper.selectOne(queryWrapper1);
            String name1 = "";
            if(ObjectUtil.isNotNull(feisuanFlightTask)){
                if (feisuanFlightTask.getTaskType() ==2) {
                    name1 = "一键起飞-";
                }else if (feisuanFlightTask.getTaskType() ==1) {
                    QueryWrapper<FeisuanInspectionTask>  queryWrapper2 = new QueryWrapper();
                    queryWrapper2.eq("flight_id", addMediaRequestDTO.getFlightId());
                    queryWrapper2.last("limit 1");

                    FeisuanInspectionTask feisuanInspectionTask = inspectionTaskMapper.selectOne(queryWrapper2);
                    if (ObjectUtil.isNotNull(feisuanInspectionTask)) {
                        name1 = feisuanInspectionTask.getPlanName() +"-";
                    }
                }
            }
            // 格式化LocalDateTime为字符串
            String formattedDateTime = localDateTime.format(formatter);
            FeisuanMedia feisuanMedia2 = new FeisuanMedia();
            feisuanMedia2.setFileName(name1+formattedDateTime);
            feisuanMedia2.setFlightId(addMediaRequestDTO.getFlightId());
            feisuanMedia2.setCreateTime(LocalDateTime.now());
            feisuanMedia2.setParentId(Long.parseLong("0"));

            feisuanMedia2.setDroneId(flightDataResponseDTO.getDroneId());
            feisuanMedia2.setFileType(1);
            feisuanMedia2.setOrganizationId(payloadDataResponseDTO.getOrganizationId());
            feisuanMedia2.setAirportId(payloadDataResponseDTO.getAirportId());
            feisuanMedia2.setDroneId(payloadDataResponseDTO.getDroneId());
            mediaMapper.insert(feisuanMedia2);
            parentId =  feisuanMedia2.getId();
        }else{
            parentId = feisuanMedia1.getId();
        }
        System.out.println("parentId = " + parentId);
        if(addMediaRequestDTO.getDir() != null && !addMediaRequestDTO.getDir().equals("")){
            //查询出当前是否建立目录
            QueryWrapper<FeisuanMedia> queryWrapper3 = new QueryWrapper();
            queryWrapper3.eq("flight_id", addMediaRequestDTO.getFlightId());
            queryWrapper3.eq("parent_id", parentId);
            queryWrapper3.eq("dir", addMediaRequestDTO.getDir());
            queryWrapper3.last("limit 1");
            FeisuanMedia feisuanMedia3 = mediaMapper.selectOne(queryWrapper3);

            if(feisuanMedia3 == null){
                FeisuanMedia feisuanMedia4 = new FeisuanMedia();
                feisuanMedia4.setFileName(addMediaRequestDTO.getDir());
                feisuanMedia4.setCreateTime(LocalDateTime.now());
                feisuanMedia4.setParentId(parentId);
                feisuanMedia4.setDir(addMediaRequestDTO.getDir());
                feisuanMedia4.setFlightId(addMediaRequestDTO.getFlightId());
                feisuanMedia4.setDroneId(flightDataResponseDTO.getDroneId());
                feisuanMedia4.setFileType(1);
                feisuanMedia4.setOrganizationId(payloadDataResponseDTO.getOrganizationId());
                feisuanMedia4.setAirportId(payloadDataResponseDTO.getAirportId());
                feisuanMedia4.setDroneId(payloadDataResponseDTO.getDroneId());
                mediaMapper.insert(feisuanMedia4);
                parentId =  feisuanMedia4.getId();
            }else{
                parentId = feisuanMedia3.getId();
            }
        }else{

        }
        System.out.println("parentId2 = " + parentId);
        //获取文件后缀
        String filename = addMediaRequestDTO.getFileName();
        int dotIndex = filename.lastIndexOf('.');
        String name = filename;
        String suffix = "";
        if (dotIndex != -1) {
            name = filename.substring(0, dotIndex); // 点前面的部分
            suffix = filename.substring(dotIndex + 1); // 点后面的部分
        } else {

        }
        feisuanMedia.setParentId(parentId);
        feisuanMedia.setAirlineId(flightDataResponseDTO.getAirlineId());
        feisuanMedia.setAirportId(flightDataResponseDTO.getAirportId());
        feisuanMedia.setFlightId(addMediaRequestDTO.getFlightId());
        feisuanMedia.setFileUrl(addMediaRequestDTO.getFileUrl());
        feisuanMedia.setFileType(2);
        feisuanMedia.setOrganizationId(flightDataResponseDTO.getOrganizationId());
        feisuanMedia.setPlanName(flightDataResponseDTO.getPlanName());
        feisuanMedia.setFileName(name);
        feisuanMedia.setSuffix(suffix);
        feisuanMedia.setTaskType(flightDataResponseDTO.getTaskType());
        feisuanMedia.setCreateTime(LocalDateTime.now());
        feisuanMedia.setDroneId(flightDataResponseDTO.getDroneId());
        feisuanMedia.setAbsoluteAltitude(addMediaRequestDTO.getAbsoluteAltitude());
        feisuanMedia.setRelativeAltitude(addMediaRequestDTO.getRelativeAltitude());
        feisuanMedia.setLongitude(addMediaRequestDTO.getLongitude());
        feisuanMedia.setLatitude(addMediaRequestDTO.getLatitude());
        feisuanMedia.setTakeTime(addMediaRequestDTO.getTakeTime());
        feisuanMedia.setDroneModelKey(addMediaRequestDTO.getDroneModelKey());
        feisuanMedia.setPayloadModelKey(addMediaRequestDTO.getPayloadModelKey());
        feisuanMedia.setOrganizationId(payloadDataResponseDTO.getOrganizationId());
        feisuanMedia.setAirportId(payloadDataResponseDTO.getAirportId());
        feisuanMedia.setDroneId(payloadDataResponseDTO.getDroneId());
        mediaMapper.insert(feisuanMedia);
        return true;
    }
}
